<template>
  <div class="main">
    <!-- 左侧菜单 -->
    <div class="sidebar">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="Logo" />
      </div>
      <ul class="menu">
        <li>
          <router-link to="/personalcenter">个人中心</router-link>
        </li>
        <li>
          <router-link to="/viewrecording">浏览记录</router-link>
        </li>
        <li class="parent-menu active">
          <a href="#" class="parent-link">账户设置
            <span class="toggle-icon">^</span>
          </a>
          <ul class="submenu" style="display: block;">
            <li><router-link to="/personalinfo">个人资料</router-link></li>
            <li><router-link to="/preference-settings" class="active">偏好设置</router-link></li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 右侧内容 -->
    <div class="content">
      <div class="content-header">
        <h1 class="page-title">偏好设置</h1>
        <router-link to="/home" class="home-button">返回主页</router-link>
      </div>

      <div class="text-container">
      <div class="preference-container">
        <!-- 说明文字 -->
        <div class="preference-intro">
          <div class="intro-icon">🎯</div>
          <div class="intro-text">
            <h3>个性化推荐设置</h3>
            <p>选择您感兴趣的商品类别，我们将为您提供更精准的推荐服务</p>
          </div>
        </div>

        <!-- 分类选择区域 -->
        <div class="categories-wrapper">
          <div 
            v-for="(subCategories, bigCategory) in categoryMapping" 
            :key="bigCategory"
            class="category-group"
          >
            <div class="category-header" @click="toggleCategory(bigCategory)">
              <div class="header-left">
                <span class="category-icon">{{ getCategoryIcon(bigCategory) }}</span>
                <span class="category-name">{{ bigCategory }}</span>
                <span class="selected-count" v-if="getSelectedCount(bigCategory) > 0">
                  已选 {{ getSelectedCount(bigCategory) }}
                </span>
              </div>
              <div class="header-right">
                <button 
                  class="select-all-btn"
                  @click.stop="toggleSelectAll(bigCategory)"
                >
                  {{ isAllSelected(bigCategory) ? '取消全选' : '全选' }}
                </button>
                <span class="expand-icon" :class="{ expanded: expandedCategories.includes(bigCategory) }">
                  ▼
                </span>
              </div>
            </div>
            
            <transition name="slide">
              <div class="sub-categories" v-show="expandedCategories.includes(bigCategory)">
                <label 
                  v-for="sub in subCategories" 
                  :key="sub"
                  class="sub-category-item"
                  :class="{ selected: selectedPreferences.includes(sub) }"
                >
                  <input 
                    type="checkbox"
                    :value="sub"
                    v-model="selectedPreferences"
                    class="checkbox-input"
                  />
                  <span class="checkbox-label">{{ sub }}</span>
                </label>
              </div>
            </transition>
          </div>
        </div>

        <!-- 已选偏好展示 -->
        <div class="selected-preferences" v-if="selectedPreferences.length > 0">
          <div class="selected-header">
            <span class="selected-title">已选偏好 ({{ selectedPreferences.length }})</span>
            <button class="clear-all-btn" @click="clearAll">清空全部</button>
          </div>
          <div class="selected-tags">
            <span 
              v-for="pref in selectedPreferences" 
              :key="pref" 
              class="preference-tag"
            >
              {{ pref }}
              <span class="remove-btn" @click="removePreference(pref)">×</span>
            </span>
          </div>
        </div>

        <!-- 保存按钮 -->
        <div class="action-buttons">
          <button class="save-btn" @click="savePreferences" :disabled="saving">
            {{ saving ? '保存中...' : '保存偏好设置' }}
          </button>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentUser, updateUserPreferences } from '@/api'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 分类映射数据
const categoryMapping = ref({})
const selectedPreferences = ref([])
const expandedCategories = ref([])
const saving = ref(false)
const loading = ref(true)

// 分类图标映射
const categoryIcons = {
  '手机数码': '📱',
  '家用电器': '🏠',
  '服饰鞋包': '👗',
  '个护美妆': '💄',
  '母婴亲子': '👶',
  '食品生鲜': '🍎',
  '运动户外': '⚽',
  '医药保健': '💊',
  '图书文娱': '📚',
  '汽车用品': '🚗',
  '宠物生活': '🐱'
}

const getCategoryIcon = (category) => {
  return categoryIcons[category] || '📦'
}

const toggleCategory = (category) => {
  const index = expandedCategories.value.indexOf(category)
  if (index > -1) {
    expandedCategories.value.splice(index, 1)
  } else {
    expandedCategories.value.push(category)
  }
}

const getSelectedCount = (bigCategory) => {
  const subs = categoryMapping.value[bigCategory] || []
  return subs.filter(sub => selectedPreferences.value.includes(sub)).length
}

const isAllSelected = (bigCategory) => {
  const subs = categoryMapping.value[bigCategory] || []
  return subs.length > 0 && subs.every(sub => selectedPreferences.value.includes(sub))
}

const toggleSelectAll = (bigCategory) => {
  const subs = categoryMapping.value[bigCategory] || []
  if (isAllSelected(bigCategory)) {
    // 取消全选
    selectedPreferences.value = selectedPreferences.value.filter(p => !subs.includes(p))
  } else {
    // 全选
    subs.forEach(sub => {
      if (!selectedPreferences.value.includes(sub)) {
        selectedPreferences.value.push(sub)
      }
    })
  }
}

const removePreference = (pref) => {
  const index = selectedPreferences.value.indexOf(pref)
  if (index > -1) {
    selectedPreferences.value.splice(index, 1)
  }
}

const clearAll = () => {
  selectedPreferences.value = []
}

const loadCategories = async () => {
  try {
    // 硬编码分类映射（与后端保持一致）
    categoryMapping.value = {
      "手机数码": [
        "CPU", "HiFi耳机", "NAS", "U盘", "一体机", "交换机", "传感器", "充电宝",
        "内存", "台式机", "墨盒", "壳膜", "复印纸", "复合机", "录音笔", "手机",
        "手环", "手表", "打印机", "扫地机器人", "扫描仪", "投影", "数据线", "显卡",
        "显示器", "智能眼镜", "智能车机", "机油", "硬盘", "硬盘盒", "碎纸机",
        "磁吸充", "移动硬盘", "笔记本", "笔记本电脑", "系统", "考勤门禁", "耳机",
        "蓝牙耳机", "读卡器", "路由器", "迷你主机", "键盘", "镜头", "电脑", "电子书",
        "鼠标", "硒鼓", "运动手表", "办公", "平板", "计算机", "相机", "相纸",
        "无人机", "科技", "贴膜", "电池", "收音机"
      ],
      "家用电器": [
        "RO净水", "中央空调", "五金", "冰柜", "冰箱", "加湿器", "卧室", "厕所",
        "台灯", "吸尘器", "吸顶灯", "吹风机", "咖啡机", "四件套", "垃圾袋", "地板",
        "地毯", "客厅", "干衣机", "应急工具", "扫拖工具", "挂画", "收纳", "收纳箱",
        "摆件", "木门", "枕芯", "毛毯", "沙发套", "油烟机", "洗碗机", "洗衣机",
        "浴室柜", "涂料", "烟灶", "炉具", "燃气灶", "燃气热水器", "电动牙刷",
        "电饭煲", "瓷砖", "盆栽", "窗帘", "筒射灯", "置物架", "装饰画", "门锁",
        "雾化器", "音箱", "餐椅", "餐厅", "香薰", "香薰蜡烛", "马桶", "龙头花洒",
        "软水机", "空气净化器", "空气炸锅", "空调", "破壁机", "足浴盆", "驱虫",
        "灭火器", "智能灯", "园艺工具", "多肉", "花种", "蒸烤", "集成灶", "电视",
        "百叶", "衣柜整理", "被芯", "插座", "电"
      ],
      "服饰鞋包": [
        "丝袜", "亲子装", "休闲裤", "休闲鞋", "内裤", "凉拖", "凉鞋儿童", "半身裙",
        "单肩", "单鞋", "围巾", "女装", "婴童装", "学生书包", "家居服", "帽子",
        "手套", "手提", "文胸", "斜挎", "棉拖", "棉服", "男装", "皮带", "皮鞋",
        "短靴", "睡衣", "篮球鞋", "背包", "背带", "背带裙", "船袜", "西裤",
        "训练短裤", "训练鞋", "跑步服", "跑步鞋", "跑鞋", "运动T", "运动鞋",
        "连衣裙", "通勤双肩", "造型", "靴子", "鞋垫", "鞋带", "骑行服", "高跟鞋",
        "登机箱", "瑜伽服", "马甲", "牛仔裤", "球衣", "球鞋", "工装"
      ],
      "个护美妆": [
        "EDP", "EDT", "乳液", "剃须刀", "化妆刷", "卷发棒", "发膜", "口红", "护发",
        "护垫", "护理套装", "护理液", "护腕", "护臀膏", "洁面", "洗发", "洗发婴儿",
        "洗衣液", "清洁", "清洁剂", "漱口水", "牙刷", "牙膏", "眼影", "粉底",
        "粉扑", "精华", "美容仪", "腮红", "身体乳", "须后", "香水", "面膜",
        "面霜", "防晒", "隐形眼镜", "湿巾", "卫生巾", "沐浴露", "理发器", "私护",
        "皮肤", "洗车工具"
      ],
      "母婴亲子": [
        "儿童", "启蒙", "奶瓶", "婴儿床", "婴儿沐浴露", "婴幼儿奶粉", "孕产营养",
        "学步鞋", "安全座椅", "少儿", "早教益智", "暖奶器", "积木", "拼插", "绘本",
        "吸奶器", "拉拉裤", "纸尿裤", "推车", "玩具", "遥控", "电动儿童"
      ],
      "食品生鲜": [
        "乳制品", "冻干", "即食", "咖啡", "啤酒", "地方特产", "坚果", "大米", "奶茶",
        "当季鲜果", "方便面", "洋酒", "溶豆", "牛排", "白酒", "米粉", "糕点", "糖果",
        "薯片", "虾", "进口食品", "速冻食品", "葡萄酒", "零食罐头", "面条", "面粉",
        "食用油", "鲜肉", "鸡蛋", "黄油", "茶", "燕窝", "肉干", "鱼", "酱料", "香料",
        "礼盒水果", "自热", "水", "功能饮料", "贝"
      ],
      "运动户外": [
        "冲浪", "哑铃", "鱼竿", "鱼线", "渔轮", "帐篷", "护具", "极限", "瑜伽", "码表",
        "臂包", "公路", "轮滑滑板", "运动相机", "阻力带", "游泳", "潜水", "训练",
        "天幕", "头盔", "三脚架"
      ],
      "医药保健": [
        "DHA", "人参", "体温计", "冬虫夏草", "情趣", "感冒", "理疗仪", "血糖仪",
        "血压计", "计生", "肠胃", "排卵", "早孕试纸", "维生素", "矿物质", "益生菌",
        "钙铁锌", "阿胶", "营养膏"
      ],
      "图书文娱": [
        "CD", "DVD", "书房", "传记", "历史", "收藏", "教材", "教辅", "文创周边",
        "文学", "生活艺术", "社科", "经管", "考试", "小说", "黑胶", "乐器", "手帐",
        "有声读物", "电影"
      ],
      "汽车用品": [
        "包围", "导航", "尾翼", "滤清器", "添加剂", "牵引", "胎压监测", "脚垫",
        "安防摄像", "车载支架", "轮胎轮毂", "镀膜打蜡", "拖车绳", "座套", "流量卡",
        "工业", "安全"
      ],
      "宠物生活": [
        "宠物玩具", "犬主粮", "猫主粮", "猫砂", "鱼粮", "鱼缸"
      ]
    }
    
    // 默认展开第一个分类
    const firstCategory = Object.keys(categoryMapping.value)[0]
    if (firstCategory) {
      expandedCategories.value.push(firstCategory)
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const loadUserPreferences = async () => {
  try {
    const res = await getCurrentUser()
    if (res?.data?.preferences) {
      selectedPreferences.value = [...res.data.preferences]
    }
  } catch (error) {
    console.error('加载用户偏好失败:', error)
  } finally {
    loading.value = false
  }
}

const savePreferences = async () => {
  if (saving.value) return
  
  saving.value = true
  try {
    const userId = userStore.userId
    if (!userId) {
      alert('请先登录')
      router.push('/user-login')
      return
    }

    await updateUserPreferences(userId, { preferences: selectedPreferences.value })
    
    // 更新本地存储
    userStore.setUserInfo({
      ...userStore.info,
      preferences: selectedPreferences.value
    })
    
    alert('偏好设置保存成功！')
  } catch (error) {
    console.error('保存偏好失败:', error)
    alert('保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

onMounted(async () => {
  if (!userStore.isLoggedIn) {
    router.push('/user-login')
    return
  }
  
  await loadCategories()
  await loadUserPreferences()
})
</script>

<style scoped>
@import '@/CSS/UserPublicCss.css';
@import '@/CSS/PreferenceSettings.css';
</style>

